//
//  ViewController.m
//  phmall
//
//  Created by admin on 2017/9/5.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "ViewController.h"
#import "RegisterVC.h"
#import "LoginVC.h"
#import "RetrievePasswordVC.h"
@interface ViewController ()<GIDSignInDelegate,GIDSignInUIDelegate>
@property(nonatomic,strong)MBProgressHUD *hud;
@end

@implementation ViewController





- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20],NSForegroundColorAttributeName:[UIColor blackColor]}];
    self.view.backgroundColor=[UIColor whiteColor];

    [self setUI];
    // Do any additional setup after loading the view, typically from a nib.
}
-(void)rightBarAction{
    
}
-(void)leftBarAction{
    [self dismissViewControllerAnimated:YES completion:nil];
//   [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
}
-(void)setUI{
    [[UINavigationBar appearance]setBarTintColor:[UIColor whiteColor]];
    UIBarButtonItem *rightBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"帮助中心"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarAction)];
    self.navigationItem.rightBarButtonItem=rightBar;
    
    UIBarButtonItem *leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回-1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    self.navigationItem.leftBarButtonItem=leftBar;
    
    UIImageView *logo=[[UIImageView alloc]init];
    [self.view addSubview:logo];
    logo.image=[UIImage imageNamed:@"logo"];
    ViewBorderRadius(logo, 10, 0, [UIColor whiteColor]);
    [logo mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset((218-RectStatus.size.height-44-64));
        make.centerX.equalTo(self.view);
        make.width.height.offset(70);
    }];
    
    UILabel *title=[[UILabel alloc]init];
    [self.view addSubview:title];
    title.font=[UIFont systemFontOfSize:24];
    title.textColor=[UIColor colorWithHexString:@"#ff9300"];
    title.text=@"PHMALL·菲淘";
    [title mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(logo.mas_bottom).with.offset(20);
        make.centerX.equalTo(self.view);
    }];

    UIButton *login=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:login];
    [login setTitle:Localized(@"登录") forState:UIControlStateNormal];
    [login setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [login setBackgroundImage:[UIImage imageNamed:@"背景渐变条"] forState:UIControlStateNormal];
//    login.backgroundColor=[UIColor colorWithHexString:@"#ff9300"];
//    ViewBorderRadius(login, 5, 1, [UIColor colorWithHexString:@"#ff9300"]);
    [login addTarget:self action:@selector(gotoLogin) forControlEvents:UIControlEventTouchUpInside];
    [login mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(title.mas_bottom).with.offset(30);
        make.height.offset(44);
        make.left.equalTo(self.view).with.offset(20);
        make.right.equalTo(self.view.mas_right).with.offset(-20);
    }];
    
    UIButton *Register=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:Register];
    [Register setTitle:Localized(@"新用户注册") forState:UIControlStateNormal];
    [Register setTitleColor:[UIColor colorWithHexString:@"#ff9300"] forState:UIControlStateNormal];
    Register.backgroundColor=[UIColor whiteColor];
    ViewBorderRadius(Register, 5, 1, [UIColor colorWithHexString:@"#ff9300"]);
    [Register addTarget:self action:@selector(gotoRegister) forControlEvents:UIControlEventTouchUpInside];
    [Register mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(login.mas_bottom).with.offset(30);
        make.height.offset(44);
        make.left.equalTo(self.view).with.offset(20);
        make.right.equalTo(self.view.mas_right).with.offset(-20);
    }];
    
    UILabel *third=[[UILabel alloc]init];
    third.text=Localized(@"第三方登录");
    third.textColor=[UIColor colorWithHexString:@"#adadad"];
    third.font=[UIFont systemFontOfSize:15];
    [self.view addSubview:third];
    [third mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(Register.mas_bottom).with.offset(90);
        make.centerX.equalTo(self.view);
    }];
    
    
    UIView *lineL=[[UIView alloc] init];
    [self.view addSubview:lineL];
    lineL.backgroundColor=[UIColor colorWithHexString:@"#adadad"];
    [lineL mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(third);
        make.left.equalTo(self.view).with.offset(40);
        make.right.equalTo(third.mas_left).with.offset(-20);
        make.height.offset(0.5);
    }];
    
    UIView *lineR=[[UIView alloc] init];
    [self.view addSubview:lineR];
    lineR.backgroundColor=[UIColor colorWithHexString:@"#adadad"];
    [lineR mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(third);
        make.left.equalTo(third.mas_right).with.offset(20);
        make.right.equalTo(self.view.mas_right).with.offset(-40);
        make.height.offset(0.5);
    }];
    
    UIButton *google=[UIButton buttonWithType:UIButtonTypeCustom];
    [google setImage:[UIImage imageNamed:@"Google"] forState:UIControlStateNormal];
    [google addTarget:self action:@selector(gooleLoginButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:google];
    [google mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(third.mas_bottom).with.offset(20);
        make.width.height.offset(40);
        make.centerX.equalTo(self.view);
    }];
    
//    FBSDKLoginButton *face = [[FBSDKLoginButton alloc] init];
    UIButton *face=[UIButton buttonWithType:UIButtonTypeCustom];
    [face setImage:[UIImage imageNamed:@"facebook"] forState:UIControlStateNormal];
    [self.view addSubview:face];
    [face addTarget:self action:@selector(loginBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [face mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(third.mas_bottom).with.offset(20);
        make.width.height.offset(40);
        make.right.equalTo(google.mas_left).with.offset(-40);
    }];
    
    UIButton *PhChat=[UIButton buttonWithType:UIButtonTypeCustom];
    [PhChat setImage:[UIImage imageNamed:@"PHCHAT"] forState:UIControlStateNormal];
    [PhChat addTarget:self action:@selector(chatBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:PhChat];
    [PhChat mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(third.mas_bottom).with.offset(20);
        make.width.height.offset(40);
        make.left.equalTo(google.mas_right).with.offset(40);
    }];
    
    GIDSignIn *signIn = [GIDSignIn sharedInstance];
    signIn.shouldFetchBasicProfile = YES;
    signIn.delegate = self;
    signIn.uiDelegate = self;
}
-(void)chatBtnClicked{
   
    
}
//谷歌
-(void)gooleLoginButtonClicked{
    self.hud =[MBProgressHUD showHUDAddedTo:self.view  animated:YES];
    self.hud.detailsLabel.text = Localized(@"加载中...");
    [[GIDSignIn sharedInstance] signOut];
    [[GIDSignIn sharedInstance] signIn];
}
//facebook
-(void)loginBtnClicked {
    self.hud =[MBProgressHUD showHUDAddedTo:self.view  animated:YES];
    self.hud.detailsLabel.text = Localized(@"加载中...");
    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    [login
     logInWithReadPermissions: @[@"public_profile", @"email"]
     fromViewController:self
     handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
         NSLog(@"facebook login result.grantedPermissions = %@,error = %@",result.grantedPermissions,error);
         if (error) {
             [self.hud hideAnimated:YES];
             NSLog(@"Process error");
         } else if (result.isCancelled) {
             NSLog(@"Cancelled");
             [self.hud hideAnimated:YES];
         } else {
             NSLog(@"Logged in");
             [self refreshUserInfo:@"facebook"];
         }
     }];
}
-(void)gotoRegister{
    RegisterVC *regis=[[RegisterVC alloc]init];
    regis.type=@"new";
    [self.navigationController pushViewController:regis animated:YES];
}
-(void)gotoLogin{
    LoginVC *login=[[LoginVC alloc]init];
    login.title=Localized(@"登录");
    login.type=@"login";
    [self.navigationController pushViewController:login animated:YES];
}
#pragma mark - GIDSignInDelegate

- (void)signIn:(GIDSignIn *)signIn
didSignInForUser:(GIDGoogleUser *)user
     withError:(NSError *)error {
    if (error) {
        [self.hud hideAnimated:YES];
        NSLog(@"%@",[NSString stringWithFormat:@"Status: Authentication error: %@", error]);
        return;
    }
    
    [self reportAuthStatus];
}
- (void)reportAuthStatus {
    GIDGoogleUser *googleUser = [[GIDSignIn sharedInstance] currentUser];
    if (googleUser.authentication) {
        NSLog(@"Status: Authenticated");
        [self.hud hideAnimated:YES];
    } else {
        // To authenticate, use Google+ sign-in button.
        NSLog( @"Status: Not authenticated");
        [self.hud hideAnimated:YES];
    }
    [self refreshUserInfo:@"google"];
}
- (void)refreshUserInfo:(NSString *)type{
    
 
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"oauth_login"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setValue:type forKey:@"type"];
    [type isEqualToString:@"google"] ? [parametersDic setValue:[GIDSignIn sharedInstance].currentUser.userID forKey:@"oauth_uid"] : [parametersDic setValue:[FBSDKAccessToken currentAccessToken].userID forKey:@"oauth_uid"];
    
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([[NSString stringWithFormat:@"%@",responseDict[@"ret"]] isEqualToString:@"200"]) {
            [self.hud hideAnimated:YES];
            if ([[NSString stringWithFormat:@"%@",responseDict[@"data"]] isEqualToString:@"0"]) {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:Localized(@"登录") message:Localized(@"登录成功，前往绑定")  preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:Localized(@"绑定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    LoginVC *login=[[LoginVC alloc]init];
                    login.type=type;
                    [self.navigationController pushViewController:login animated:YES];
                }];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:Localized(@"取消") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alert addAction:okAction];
                [alert addAction:cancelAction];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                [self dismissViewControllerAnimated:YES completion:nil];
//                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:[NSNumber numberWithBool:YES]];
            }
        }
    } andFailure:^{
         
    }];
    
    
}
- (void)signIn:(GIDSignIn *)signIn
didDisconnectWithUser:(GIDGoogleUser *)user
     withError:(NSError *)error {
    if (error) {
        NSLog(@"%@", [NSString stringWithFormat:@"Status: Failed to disconnect: %@", error]);
    } else {
        NSLog(@"%@",[NSString stringWithFormat:@"Status: Disconnected"]);
    }
    [self reportAuthStatus];
}

- (void)presentSignInViewController:(UIViewController *)viewController {
    [[self navigationController] pushViewController:viewController animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
